<?php
/**
 * Created by PhpStorm.
 * User: xiangpeng
 * Date: 2016/12/28
 * Time: 0:26
 */

namespace Common\Model;


class GoodsModel extends BaseModel
{
    //主键
    protected $pk  ='gid';
    //操作那张表
    protected $tableName = 'goods';
    protected $_validate = [
        ['gname','require','商品名称不能为空',1,3],
        ['gnumbers','require','商品货号不能为空',1,3],
        ['marketprice','require','市场价不能为空',1,3],
        ['shopprice','require','商城价不能为空',1,3],
        ['click','require','请添加点击次数',1,3],
        ['stocks','require','库存不能为空',1,3],
        ['pic','require','请添加列表图册',1,3],

    ];

    //添加方法
    public function store(){
        //验证  三张表添加，分表进数据库，但是必须一表一验证
        //1.商品表验证，添加之前先验证
        if(!$this->create()){
            return ['status'=>'faild','message'=>$this->getError()];die;
        }

        //3.1执行商品详情表的验证
        $detailModel= new DetailModel();
        if(!$detailModel->create()){
            return ['status'=>'faild','message'=>$detailModel->getError()];die;
        }
        if(!isset($_POST['detailPic'])){
            return ['status'=>'faild','message'=>'请上传上商品图册'];die;

        }
        //dd($_POST);die;
        //2.执行商品添加,组合数据
        $data  =  [
            'gname'             => $_POST[ 'gname' ] ,
            'unit'              => $_POST['unit'],
            'marketprice'       => $_POST['marketprice'],
            'shopprice'         => $_POST['shopprice'],
            'gnumbers'         => $_POST['gnumbers'],
            'click'             => $_POST['click'],
            'stocks'            => $_POST['stocks'],
            'pic'               => $_POST['pic'],
            'time'              => time(),
            'intro'             => $_POST['intro'],
            'service'           => $_POST['service'],
            'tid'               => $_POST['tid'],
            'uid'               => session(id),
            'bid'               => $_POST['bid'],
            'cid'               => $_POST['cid'],

        ];
        //dd($this->data);die;
        //2.2执行添加
        $gid = $this->add($data);

        //4.执行商品详情表添加
        //4.1处理大中小图
        $image = new \Think\Image();
        $small = '';
        $medium = '';
        $big   = '';
        //4.2将数据遍历重组
        foreach ($_POST['detailPic'] as $k=>$v){
            //dd($v);
            $image->open($v);
            // 4.3生成一个固定大小为150*150的缩略图并保存为thumb.jpg
            //4.4处理路径
            $bigPath = dirname($v).'/big_'.basename($v);
            $mediumPath = dirname($v).'/medium_'.basename($v);
            $smallPath = dirname($v).'/small_'.basename($v);
            //4.5缩略图片
            $image->thumb(800, 800)->save($bigPath);
            $image->thumb(400,400)->save($mediumPath);
            $image->thumb(80,80)->save($smallPath);
            //4.6获得路径
            $small   .=      $smallPath.',';
            $medium  .=      $mediumPath . ',';
            $big     .=      $bigPath . ',';
        }
        //4.7重组data数据
        $data = [
            'small'   =>      rtrim($small,','),
            'medium'  =>      rtrim($medium,','),
            'big'     =>      rtrim($big, ','),
            'intro'   =>      $_POST['intro'],
            'service' =>      $_POST['service'],
            'gid'     =>      $gid,
        ];
        //dd($data);die;
       //4.8调用模型执行添加动作
       // dd($detailModel->data);DIE;
        $detailModel->add($data);

        //5.商品属性表的添加
        $goodsAttModel= new GoodsAttrModel();
        //属性添加
        foreach ($_POST['attr'] as $k=>$v){
            //重组数据
            if($v){
                $data = [
                    'gtvalue'=>$v ,
                    'added'=>0,
                    'taid' =>$k,
                    'gid'  =>$gid,
                ];
                //执行添加动作
                $goodsAttModel->add($data);
            }
        }
        //规格添加
        foreach ($_POST['spec'] as $k=>$v){
            //重组数据
            foreach($v['value'] as $kk=>$vv){
                $data= [
                    'gtvalue'=>$vv,
                    'added'=>$v['added'][$kk],
                    'taid'=> $k,
                    'gid'=>$gid,
                ];
                //执行添加动作
                $goodsAttModel->add($data);
            }
        }
        //dd($data);
        return ['status'=>'success','message'=>'操作成功'];
    }

    //商品的编辑方法
    public function edit($gid){
        //1.商品表验证，添加之前先验证
        if(!$this->create()){
            return ['status'=>'faild','message'=>$this->getError()];die;
        }

        //3.1执行商品详情表的验证及更改
        $detailModel= new DetailModel();
        if(!$detailModel->create()){
            return ['status'=>'faild','message'=>$detailModel->getError()];die;
        }
        if(!isset($_POST['detailPic'])){
            return ['status'=>'faild','message'=>'请上传上商品图册'];die;

        }

        //2.执行商品更改,组合数据
        $data  =  [
            'gname'             => $_POST[ 'gname' ] ,
            'unit'              => $_POST['unit'],
            'marketprice'       => $_POST['marketprice'],
            'shopprice'         => $_POST['shopprice'],
            'gnumbers'         => $_POST['gnumbers'],
            'click'             => $_POST['click'],
            'stocks'            => $_POST['stocks'],
            'pic'               => $_POST['pic'],
            'time'              => time(),
            'intro'             => $_POST['intro'],
            'service'           => $_POST['service'],
            'tid'               => $_POST['tid'],
            'uid'               => session(id),
            'bid'               => $_POST['bid'],
            'cid'               => $_POST['cid'],

        ];
        //dd($this->data);die;
        //2.2执行更改
        $fid= $this->where("gid={$gid}")->save($data);
        //dd($DD);DIE;

        //4.执行商品详情表更改
        //4.1处理大中小图
        $image = new \Think\Image();
        $small = '';
        $medium = '';
        $big   = '';
        //4.2将数据遍历重组
        foreach ($_POST['detailPic'] as $k=>$v){
            //Uploads/2016-12-31/big_big_58678531b02fa.jpg
            $dirName = dirname($v);
            $fileName = basename($v);
            if(strrchr($fileName,'_')){
                $fileName = ltrim(strrchr($fileName,'_'),'_');
            }
            $path = $dirName .'/'.$fileName;
            $image->open($path);
            // 4.3生成一个固定大小为150*150的缩略图并保存为thumb.jpg
            //4.4处理路径
            $bigPath = dirname($path).'/big_'.basename($path);
            $mediumPath = dirname($path).'/medium_'.basename($path);
            $smallPath = dirname($path).'/small_'.basename($path);
            //4.5缩略图片
            $image->thumb(800, 800)->save($bigPath);
            $image->thumb(400,400)->save($mediumPath);
            $image->thumb(80,80)->save($smallPath);
            //4.6获得路径
            $small   .=      $smallPath.',';
            $medium  .=      $mediumPath . ',';
            $big     .=      $bigPath . ',';
        }
        //4.7重组data数据
        $data = [
            'small'   =>      rtrim($small,','),
            'medium'  =>      rtrim($medium,','),
            'big'     =>      rtrim($big, ','),
            'intro'   =>      $_POST['intro'],
            'service' =>      $_POST['service'],
            'gid'     =>      $gid,
        ];
        //dd($data);die;
        //4.8调用模型执行更改动作
        //注意变量覆盖问题！！！！！！！！！！！！！！！！
        //获得要修改的主键
        $gdid =$detailModel->where("gid={$gid}")->getField('gdid');
        $detailModel->where("gdid={$gdid}")->save($data);

        //5.商品属性表的编辑
        $goodsAttModel= new GoodsAttrModel();
        //执行删除动作
        $goodsAttModel->where("gid={$gid}")->delete();
        //dd($gtid);die;
        //属性更改
        //$_POST['attr'];die;
        foreach ($_POST['attr'] as $k=>$v){
            //重组数据
            if($v){
                $data = [
                    'gtvalue'=>$v ,
                    'added'=>0,
                    'taid' =>$k,
                    'gid'  =>$gid,
                ];
                //dd($data);
                //执行添加动作
                $goodsAttModel->add($data);

            }
        }
        //规格编辑
        foreach ($_POST['spec'] as $k=>$v){
            //重组数据
            foreach($v['value'] as $kk=>$vv){
                $data= [
                    'gtvalue'=>$vv,
                    'added'=>$v['added'][$kk],
                    'taid'=> $k,
                    'gid'=>$gid,
                ];
                //dd($data);die;
                //执行添加动作
                $goodsAttModel->add($data);

            }
        }
        return ['status'=>'success','message'=>'操作成功'];
    }
    //商品的删除
    public function del($gid){
        //dd($gid);die;
        //将线上的图片删除
        //先删除列表图 //获得路径
        $path = (new GoodsModel())->where("gid={$gid}")->getField('pic');
        ////将列表图删除
        unlink($path);
        //echo 2;DIE;
        //再删详情图
        //获得详情图路径
        $path = (new DetailModel())->where("gid={$gid}")->getField('big');
        //Uploads/2017-01-03/big_586b55aa58956.jpg,Uploads/2017-01-03/big_586b55ae4c0a0.jpg,Uploads/2017-01-03/big_586b55b3cd5c8.png
        //获得原图所在的路径
        $path = explode(',',$path);
        //dd($path);die;
        $dirName = dirname($path[0]);
        //dd($dirName);DIE;
        //获得原图路径
        foreach ($path as $k=>$v){
            $fileName = ltrim(strrchr(basename($v),'_'),'_');
            //将线上图片路径组合成一个数组
            $arr[] = $dirName .'/'.$fileName;
            $arr[] = $dirName .'/'.'small_'.$fileName;
            $arr[] = $dirName .'/'.'medium_'.$fileName;
            $arr[] = $dirName .'/'.'big_'.$fileName;
            //Uploads/2017-01-02/small_586a0d142d10b.jpgUploads/2017-01-02/small_586a0d142d10b.jpg
            //循环遍历删除
            foreach ($arr as $kk=>$vv){
                //判断文件或目录是否存在
                if(file_exists($vv)){
                    unlink($vv);
                }
            }
            //因为会累加所以每循环一次就置空
            $arr= [];
        }
        //die;
        //实例化商品表
        $goodsModel= new GoodsModel();
        //实例化商品详情表
        $detailModel= new DetailModel();
        //实力化商品属性表
        $goodsAttrModel= new GoodsAttrModel();
        //dd($gid);DIE;
        //删除商品表的数据
        if(!$goodsModel->where("gid={$gid}")->delete()){
            return ['status'=>'faild','message'=>'删除失败'];
        }
        //删除商品详情表的数据
        if(!$detailModel->where("gid={$gid}")->delete()){
            return ['status'=>'faild','message'=>'删除失败'];
        }
        //删除商品属性表的数据
        if(!$goodsAttrModel->where("gid={$gid}")->delete()){
            return ['status'=>'faild','message'=>'删除失败'];
        }else{
            return ['status'=>'success','message'=>'删除成功'];
        }
    }


}